<template>
  <el-dialog
    append-to-body
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    :wrapperClosable="false"
    :title="$t('productCenter.addCategories')"
    width="80%"
    top="0"
    :visible.sync="dialogAdd"
    :before-close="closeDialog"
    style="margin: 0;"
  >
    <el-form label-position="top" class="addCateBox">
      <el-row :gutter="60">
        <el-col :span="8">
          <el-form-item :label="$t('productCenter.channel')">
            <el-select
              v-model="channel"
              placeholder="Please Select"
              @change="channelChange"
              style="width:270px"
            >
              <el-option
                v-for="item in channelList"
                :key="item.dicCode"
                :label="item.dicName"
                :value="item.dicCode"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item :label="$t('productCenter.category')">
            <el-cascader
              :options="categoryList"
              v-if="showCascader"
              ref="cascaderAddr"
              :props="props"
              :show-all-levels="false"
              checkStrictly="true"
              emitPath="false"
              @change="handelChange"
              v-model="addModel[addModel.channel + 'list']"
            ></el-cascader>
            <!-- <el-button @click="handelChange" size="small">{{$t('productCenter.saveCategories')}}</el-button> -->
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item class="selected-form" :label="$t('productCenter.selected')">
        <div v-for="(channel, key) in addModel.addList" :key="key">
          <el-tag
            v-for="(tag, index) in channel"
            :key="index"
            closable
            @close="handleClose(key, tag, index)"
            type="success"
          >{{tag.label}}</el-tag>
        </div>
      </el-form-item>
      <el-form-item>
        <el-button size="small" @click="saveAddCate">{{$t('save')}}</el-button>
        <el-button size="small" @click="closeDialog">{{$t('cancel')}}</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>
<script>
import { getCatalogById } from '@/api/product'
import { cloneDeep } from 'lodash'
import { mapGetters } from 'vuex'
import { common } from '@/mixins/common'
export default {
  props: {
    orgList: {
      type: Array
    },
    countryTypes: {
      type: Array
    }
  },
  mixins: [common],
  data () {
    return {
      channel: '',
      showCascader: false,
      channelList: [],
      dialogAdd: false,
      categoryList: [],
      catalogDatas: [],
      props: {
        multiple: true,
        value: 'id',
        label: 'categoryName'
      },
      addModel: {
        channel: '',
        catalogId: [],
        addList: {}
      }
    }
  },
  created () {
    this.channelList = this.lookupItems.CHANNEL
    this.channelList.forEach(item => {
      this.$set(this.addModel, item.dicCode + 'list', [])
    })
  },
  computed: {
    ...mapGetters(['lookupItems'])
  },
  methods: {
    // 数据初始化
    initDatas (initDatas, channel) {
      if (channel) {
        this.addModel.channel = channel
        this.channel = channel
      } else {
        this.addModel.channel = this.channelList[0].dicCode
        this.channel = this.channelList[0].dicCode
      }
      if (initDatas) {
        initDatas = cloneDeep(initDatas)
        const keys = Object.keys(initDatas)
        keys.forEach(key => {
          initDatas[key].forEach(category => {
            if (!this.addModel[key + 'list']) {
              this.$set(this.addModel, key + 'list', [])
            }
            this.addModel[key + 'list'].push(category.list)
          })
        })
        this.addModel.addList = initDatas
      }
      this.changeSelect(this.channel)
    },
    // 选择channel
    channelChange (val) {
      this.changeSelect()
    },
    // category数据选中
    handelChange (val) {
      this.$nextTick(_ => {
        const selNode = this.$refs.cascaderAddr.getCheckedNodes(true)
        const selectData = []
        selNode.forEach((item, index) => {
          selectData.push({
            channel: this.addModel.channel,
            label: item.label,
            list: val[index],
            orgId: item.path[0]
          })
        })
        this.$set(this.addModel.addList, this.addModel.channel, selectData)
      })
    },
    // 删除选中数据
    handleClose (key, tag, index) {
      this.addModel.addList[key].splice(
        this.addModel.addList[key].indexOf(tag),
        1
      )
      const channelList = cloneDeep(this.addModel[key + 'list'])
      channelList.splice(index, 1)
      this.$set(this.addModel, key + 'list', channelList)
    },
    // 关闭按钮点击
    closeDialog (done) {
      this.$confirm(this.$t('closeDrawerTip'), {
        confirmButtonText: this.$t('confirmYes'),
        cancelButtonText: this.$t('confirmNo')
      })
        .then(() => {
          this.dialogAdd = false
          this.$nextTick(_ => {
            this.$emit('closeDialog')
          })
          done()
        })
        .catch(() => {})
    },
    // 展示category弹窗
    showAddProduct (initDatas, channel) {
      this.dialogAdd = true
      this.initDatas(initDatas, channel)
    },
    // 根据channel获取category数据树
    changeSelect () {
      const self = this
      this.showCascader = false
      const channelCodeList = []
      channelCodeList.push(this.channel)
      getCatalogById(this.channel).then(response => {
        const data = response
        if (Number(data.code) === 1) {
          const obj = data.obj || []
          obj.forEach(item => {
            if (item.children && item.children.length > 0) {
              item.children.forEach(subItem => {
                if (!(subItem.children && subItem.children.length > 0)) {
                  subItem.disabled = true
                }
              })
            } else {
              item.disabled = true
            }
          })
          self.categoryList = obj
          this.addModel.channel = this.channel
          this.showCascader = true
        } else {
          this.$confirm(this.$t(data.code), {
            confirmButtonText: this.$t('confirmOK'),
            showCancelButton: false
          })
        }
      })
        .catch(error => {
          this.$confirm(error, {
            confirmbuttontext: this.$t('confirmOK'),
            showcancelbutton: false
          })
        })
    },
    // 保存按钮点击
    saveAddCate () {
      this.dialogAdd = false
      this.$emit('setValue', this.addModel.addList)
    }
  }
}
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
/deep/ .el-input {
  margin-bottom: 0;
}
.selected-form {
  /deep/ .el-form-item__content {
    padding: 5px 10px;
    width: 100%;
    min-height: 100px;
    border: 1px solid #979797;
  }
}
.addCateBox {
  .el-tag {
    margin-right: 10px;
  }
}
/deep/ .el-cascader {
  line-height: 30px !important;
  width: 270px !important;
  .el-input--suffix {
    height: auto !important;
    min-height: 30px !important;
  }
}
</style>
